import { omit } from 'lodash-es';
import type { TreeDataItem as ATreeDataItem } from 'ant-design-vue/es/tree/Tree';

export interface TreeDataItem extends ATreeDataItem {
  children: any;
}
export const flatTree = (treeData) => {
  const flatData: any[] = [];
  const flatFn = (data) => {
    data.forEach((item) => {
      if (item.children && item.children.length) {
        flatData.push(omit(item, ['children']));
        flatFn(item.children);
      } else {
        flatData.push(omit(item, ['children']));
      }
    });
  };
  flatFn(treeData);
  return flatData;
};
/**
 * 渲染部门至树形控件
 * @param {Array} depts 所有部门
 * @param {Number | null} parentId 父级部门ID
 * @param {number[]|string[]} keyPath ID路径
 */
export const formatDept2Tree = (
  depts: API.DeptListPageResultItem[],
  parentid: string | number | null = null,
  keyPath: (string | number)[] = [],
): TreeDataItem[] => {
  // 当 parentid 未指定时，自动检测根节点
  if (parentid === null || parentid === undefined) {
    // 分析数据，找出所有可能的根节点条件
    const parentIds = depts.map(item => item.parentId);
    
    // 情况1：如果存在 parentId 为 null/undefined 的节点，视为根节点
    const hasNullParent = parentIds.some(id => id === null || id === undefined);
    // 情况2：如果存在 parentId 为空字符串的节点，视为根节点
    const hasEmptyParent = parentIds.some(id => id === '');
    // 情况3：如果存在 parentId 为 "0" 的节点，视为根节点
    const hasZeroParent = parentIds.some(id => id === '0' || id === 0);
    
    // 根据数据特征确定根节点的 parentId 值
    let rootParentId: string | number | null = null;
    if (hasNullParent) {
      rootParentId = null;
    } else if (hasEmptyParent) {
      rootParentId = '';
    } else if (hasZeroParent) {
      rootParentId = '0';
    } else {
      // 如果无法确定根节点，尝试查找不在 id 列表中的 parentId
      const allIds = new Set(depts.map(item => item.id));
      const potentialRoots = parentIds.filter(id => !allIds.has(id));
      rootParentId = potentialRoots.length > 0 ? potentialRoots[0] : null;
    }
    
    // 递归构建整棵树
    return formatDept2Tree(depts, rootParentId, []);
  }

  // 递归构建子树
  return depts
    .filter((item) => item.parentId === parentid)
    .map((item) => {
      const _keyPath = keyPath.concat(parentid !== null ? parentid : []);
      const children = formatDept2Tree(depts, item.id, _keyPath);
      
      return {
        ...item,
        keyPath: _keyPath,
        title: item.name,
        key: item.id,
        value: item.id,
        dataModel: item.dataModel,
        formData: item,
        children: children.length > 0 ? children : null,
      };
    });
};

/**
 * 渲染菜单至树形控件
 * @param {Array} menus 所有菜单
 * @param {Number | null} parentId 父级菜单ID
 * @param {number[]|string[]} keyPath ID路径
 */
export const formatMenu2Tree = (
  menus: API.MenuListResult,
  parentId: string = '0',
  keyPath: string[] = [],
): TreeDataItem[] => {
  return menus
    .filter((item) => item.parentId === parentId)
    .map((item) => {
      const _keyPath = keyPath.concat(parentId || []);
      const arr = formatMenu2Tree(menus, item.menuId, _keyPath);
      return Object.assign(item, {
        keyPath: _keyPath,
        title: item.menuName,
        key: item.menuId,
        value: item.menuId,
        formData: item,
        children: arr.length ? arr : null,
      });
    });
};

/**
 * 在树中根据ID找child
 * @param {string|number} id
 * @param {any[]} treeData 树形数据
 * @param {string} keyName 指定ID的属性名，默认是id
 * @param {string} children 指定children的属性名，默认是children
 */
export const findChildById = <T = any>(
  id,
  treeData: T[] = [],
  keyName = 'id',
  children = 'children',
) => {
  return treeData.reduce((prev, curr) => {
    if (curr[keyName] === id) {
      return curr;
    }
    if (prev) {
      return prev;
    }
    if (curr[children]?.length) {
      return findChildById(id, curr[children], keyName, children);
    }
  }, undefined);
};
